package posts

import (
	"community-service/cmd/api/internal/models/model"
	"community-service/cmd/api/internal/svc"
	"community-service/cmd/api/internal/types"
	e "community-service/pkg/errorx"
	"context"
	"google.golang.org/grpc/codes"
	"gorm.io/gorm"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdatePostLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUpdatePostLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePostLogic {
	return &UpdatePostLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpdatePostLogic) UpdatePost(req *types.PostUpdateReq) (resp *types.Empty, err error) {
	if req.Id <= 0 {
		return nil, e.NewGrpcErr(codes.InvalidArgument, e.ErrorParam)
	}

	postQuery := l.svcCtx.DB.WithContext(l.ctx).Model(&model.CsCommunityPost{})

	// 检查帖子是否存在
	var existPost model.CsCommunityPost
	if err = postQuery.Session(&gorm.Session{}).Where("id = ?", req.Id).Find(&existPost).Error; err != nil {
		return nil, e.NewGrpcErr(codes.Internal, e.DBError)
	}

	if existPost.ID == 0 {
		return nil, e.NewGrpcErr(codes.NotFound, e.PostNotFound)
	}

	// 更新帖子
	updateData := make(map[string]interface{})

	if req.Title != "" {
		updateData["title"] = req.Title
	}
	if req.Content != "" {
		updateData["content"] = req.Content
	}
	updateData["updated_at"] = time.Now()

	if len(updateData) > 0 {
		if err = postQuery.Where("id = ?", req.Id).Updates(updateData).Error; err != nil {
			return nil, e.NewGrpcErr(codes.Internal, e.DBError)
		}
	}

	return &types.Empty{}, nil
}
